package com.karrim.server.util.array.abstr;

import com.karrim.server.util.array.def.Array;
import com.karrim.server.util.array.exception.ElementNotFoundException;
import java.util.Iterator;

/**
 *
 * @author andrea.cantafio
 */
public abstract class AbstractArray<T extends Object> implements Array<T> {

    public AbstractArray() {
    }

    public AbstractArray(Array<T> array) {
        Iterator<T> iterator = array.iterator();
        if (iterator.hasNext()) {
            T t = iterator.next();
            add(t);
            componentType = (Class<T>) t.getClass();
        }
        while (iterator.hasNext()) {
            add(iterator.next());
        }
    }

    @Override
    public boolean contains(T t) {
        Iterator<T> iterator = iterator();
        while (iterator.hasNext()) {
            /* Comparing by address */
            if (iterator.next() == t) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Class<T> getComponentType() {
        return componentType;
    }

    @Override
    public Integer getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public AbstractArray<T> remove(T t) throws ElementNotFoundException {
        Iterator<T> iterator = iterator();
        while (iterator.hasNext()) {
            if (iterator.next().equals(t)) { // Comparing by address
                iterator.remove();
                size--;
                return this;
            }
        }
        throw new ElementNotFoundException(t);
    }

    @Override
    public T[] toArray() {
        Iterator<T> iterator = iterator();
        T[] os = (T[]) new Object[size];
        //T[] os = (T[]) java.lang.reflect.Array.newInstance((componentType = clazz), size);
        for (int i = 0; i < size; i++) {
            os[i] = iterator.next();
        }
        return os;
    }

    @Override
    public String toString() {
        if (isEmpty()) {
            return "{}";
        }
        String str = "{";
        Iterator<T> iterator = iterator();
        String delimiter = ", ";
        while (iterator.hasNext()) {
            str += "" + iterator.next() + delimiter;
        }
        return str.substring(0, str.length() - delimiter.length()).concat("}");
    }
    private Class<T> componentType;
    protected Integer size = 0;
}
